<template>
  <div class="payment-method">
    <router-link v-if="type == 'buy'" to="/order">
      <van-nav-bar title="在线支付" left-arrow />
    </router-link>
    <router-link v-if="type == 'exchange'" to="/user">
      <van-nav-bar v-if="type == 'exchange'" title="余额充值" left-arrow />
    </router-link>

    <div v-html="payForm" hidden></div>
    <div class="countdown" v-if="type == 'buy'">
      <span class="time-label">剩余支付时间：</span>
      <br />
      <span class="remaining-time">{{ remainTime }}</span>
    </div>
    <van-divider />
    <div class="order-info" v-if="type == 'buy'">
      <van-row>
        <van-col span="20" class="good-info">{{ goodInfo }}</van-col>
        <van-col span="4" class="good-price">￥{{ totalPrice }}</van-col>
      </van-row>
    </div>
    <!--充值金额选择-->
    <van-radio-group v-if="type == 'exchange'" class="exchange" v-model="selectedAmount" direction="horizontal">
      <van-radio v-for="amount in amounts" :key="amount" :name="amount">{{ amount }}元</van-radio>
      <br />
      <van-radio class="customAmount" :name="0">
        <van-field v-model="customAmount" label="自定义金额" type="number" placeholder="输入自定义金额" />
      </van-radio>
    </van-radio-group>
    <!-- 支付类型选择表单 -->
    <van-radio-group v-model="payMethod">
      <van-cell-group>
        <van-cell v-if="type == 'buy'" class="balancepay" title="余额支付" clickable @click="payMethod = '0'" icon="gold-coin">
          <template #right-icon>
            <van-radio name="0" />
          </template>
        </van-cell>
        <van-cell class="alipay" title="支付宝支付" clickable @click="payMethod = '1'" icon="alipay">
          <template #right-icon>
            <van-radio name="1" />
          </template>
        </van-cell>
      </van-cell-group>
    </van-radio-group>
    <van-button v-if="type == 'buy' && remainTime !== '该订单已过期'" type="primary" block @click="goToPayment"> 去支付 </van-button>
    <van-button v-if="type == 'exchange' && remainTime !== '该订单已过期'" type="primary" block @click="goToExchange"> 充值 </van-button>
    <van-button v-if="remainTime == '该订单已过期'" type="danger" block @click="cancelOrder"> 取消订单 </van-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      totalPrice: 0, //总价
      orderNo: null, //订单号
      orderInfo: {
        itemList: [],
      }, //订单信息
      remainTime: null, //剩余时间
      payMethod: '0', //支付方式
      goodInfo: '', //商品信息
      payForm: '', //支付表单
      payNo: '',
      type: '', //支付类型
      selectedAmount: '', // 存储选择的充值额度
      customAmount: '', // 存储自定义输入的充值额度
      amounts: ['10', '20', '50', '100'], // 预设的充值额度选项
      isCustomDisabled: false, // 控制自定义输入框是否被禁用
    };
  },
  mounted() {
    this.type = this.$route.query.type;
    if (this.type == 'buy') {
      this.orderNo = this.$route.query.orderNo;
      this.getOrderInfo();
    }
    if (this.type == 'exchange') {
      this.payMethod = '1';
    }
  },
  methods: {
    //通过订单号获取订单详情信息
    getOrderInfo() {
      this.req.get('/order/item', { params: { orderNo: this.orderNo } }).then((res) => {
        if (res.status == 200) {
          this.orderInfo = res.data;
          this.payNo = res.data.payNo;
          this.startCountdown();
          this.getGoodInfo();
        }
      });
    },
    //开始支付剩余时间倒计时
    startCountdown() {
      this.updateRemainingTime(); // 初始化剩余时间
      this.countdownTimer = setInterval(() => {
        this.updateRemainingTime(); // 每秒更新剩余时间
      }, 1000);
    },
    //停止到技术
    stopCountdown() {
      clearInterval(this.countdownTimer); // 清除定时器
    },
    //更新时间
    updateRemainingTime() {
      const createTime = new Date(this.orderInfo.createTime); // 使用订单创建时间
      const currentTime = new Date(); // 当前时间
      const remainTime = createTime.getTime() + 30 * 60 * 1000 - currentTime.getTime(); //转为时间戳
      if (remainTime <= 0) {
        this.remainTime = '该订单已过期';
        this.stopCountdown(); // 停止定时器
      } else {
        const minutes = Math.floor(remainTime / 1000 / 60);
        const seconds = Math.floor((remainTime / 1000) % 60);
        this.remainTime = `${minutes}分${seconds}秒`;
      }
    },
    //获取商品信息
    getGoodInfo() {
      var goodInfo = '';
      this.orderInfo.itemList.forEach((order) => {
        goodInfo = goodInfo + order.dish.name + '[' + order.taste.name + ']*' + order.quantity + ' ';
      });
      this.goodInfo = goodInfo;
      this.totalPrice = this.orderInfo.totalPrice;
    },
    //去支付
    goToPayment() {
      if (this.payMethod == '0') {
        //余额支付
        this.$router.push({
          path: '/payment',
          query: {
            payNo: this.payNo,
            totalPrice: this.totalPrice,
          },
        });
      } else if (this.payMethod == '1') {
        //支付宝支付
        this.getAlipayForm();
        // this.alipay();
      }
    },
    //获取阿里支付表单
    getAlipayForm() {
      this.req.get('/order/alipay', { params: { payNo: this.payNo } }).then((res) => {
        this.payForm = res.data.payForm;
        this.payNo = res.data.payNo;
        this.alipay();
      });
    },
    //支付宝支付
    alipay() {
      this.$nextTick(() => {
        console.log('提交支付表单', this.payForm);
        if (this.payForm == '') {
          return;
        }
        this.showIsPay = true;
        document.forms[0].setAttribute('target', '_blank');
        document.forms[0].submit();
        //跳转到确认支付结果页面
        this.$router.push({ path: '/alipayresult', query: { payNo: this.payNo, type: this.type } });
      });
    },
    //前往充值
    goToExchange() {
      let amount = null;
      if (this.selectedAmount == '0') {
        //自定义金额
        amount = parseInt(this.customAmount);
      } else {
        //指定金额
        amount = parseInt(this.selectedAmount);
      }
      if (!amount) {
        this.$notify({
          type: 'danger',
          message: '请选择输入要充值的金额',
        });
      }
      this.getExchangeForm(amount);
    },
    //取消订单
    cancelOrder() {
      this.req.post('/order/cancel', { orderNo: this.orderNo }).then((res) => {
        if (res.data.status == 200) {
          this.$notify({
            type: 'success',
            message: res.msg,
          });
          this.$router.push({ path: '/order', query: { status: '0' } });
        } else {
          this.$notify({
            type: 'danger',
            message: res.msg,
          });
        }
      });
    },
    //获取充值form
    getExchangeForm(amount) {
      this.req.get('/user/exchange/alipay', { params: { amount } }).then((res) => {
        this.payForm = res.data.payForm;
        this.payNo = res.data.payNo;
        this.alipay();
      });
    },
  },
};
</script>

<style lang="less" scoped>
//时间倒计时样式
.countdown {
  margin: 20px;
  text-align: center;
  font-size: 16px;
  .remaining-time {
    font-weight: bold;
    font-size: 25px;
    color: tomato;
  }
}
//订单信息样式
.order-info {
  background-color: #fff;
  height: 44px;
  padding: 0 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .van-row {
    width: 100%;
    .good-price {
      color: tomato;
      font-size: 18px;
      font-weight: bold;
      text-align: right;
    }
  }
}
.balancepay {
  .van-icon {
    color: orange;
  }
}
.alipay {
  .van-icon {
    color: blue;
  }
}
//确认支付对话框样式
.isPay {
  padding: 30px 10px;
  .title {
    text-align: center;
    margin-bottom: 20px;
    color: #333;
  }
  .buttons {
    display: flex;
    justify-content: center;
    .van-col {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .van-button {
      width: 120px;
      margin: 0 auto;
    }
  }
}
//充值额度样式
.exchange {
  background-color: #fff;
  padding: 20px;
  .customAmount {
    margin: 10px 0;
  }
}
</style>
